package com.imooc.deliveryman.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imooc.deliveryman.dao.DeliverymanDao;
import com.imooc.deliveryman.dto.OrderMessageDTO;
import com.imooc.deliveryman.enummeration.DeliverymanStatus;
import com.imooc.deliveryman.po.DeliverymanPo;
import com.rabbitmq.client.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeoutException;

/**
 * ProjectName deliveryman
 *
 * @author xieyucan
 * <br>CreateDate 2022/9/20 17:33
 */
@Slf4j
@Service
public class OrderMessageService {

    @Autowired
     private DeliverymanDao deliverymanDao;

    ObjectMapper objectMapper=new ObjectMapper();

    DeliverCallback deliverCallback=((consumerTag, message) -> {
        String messageBody=new String(message.getBody());
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("43.138.244.235");
        connectionFactory.setPort(5672);
        connectionFactory.setPassword("1234");
        connectionFactory.setUsername("admin");

        try {
            OrderMessageDTO orderMessageDTO = objectMapper.readValue(messageBody, OrderMessageDTO.class);
            /*-----------------------------------------*/
            List<DeliverymanPo> deliverymanPos = deliverymanDao.selectDeliverymanByStatus(DeliverymanStatus.AVALIABLE);
            //练习，我就不讲究了，选择第一个骑手
            orderMessageDTO.setDeliverymanId(deliverymanPos.get(0).getId());
            /*-----------------------------------------*/

            try(Connection connection=connectionFactory.newConnection();
                Channel channel=connection.createChannel()){
                String messageToSend = objectMapper.writeValueAsString(orderMessageDTO);
                channel.basicPublish(
                        "exchange.order.restaurant",
                        "key.order",
                        null,
                        messageToSend.getBytes()
                );
            }
        }catch (JsonProcessingException | TimeoutException e) {
            log.error(e.getMessage(),e);
        }
    });

    @Async
    public void handleMessage() throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("43.138.244.235");
        connectionFactory.setPort(5672);
        connectionFactory.setPassword("1234");
        connectionFactory.setUsername("admin");

        try (Connection connection=connectionFactory.newConnection();
             Channel channel=connection.createChannel()){
            channel.exchangeDeclare(
                    "exchange.order.deliveryman",
                    BuiltinExchangeType.DIRECT,
                    true,
                    false,
                    null);

            channel.queueDeclare(
                    "queue.deliveryman",
                    true,
                    false,
                    false,
                    null
            );
            channel.queueBind(
                    "queue.deliveryman",
                    "exchange.order.deliveryman",
                    "key.deliveryman"
            );
            channel.basicConsume(
                    "queue.deliveryman",
                    true,
                    deliverCallback,
                    consumerTag -> {}
            );
            while (true){
                Thread.sleep(10000000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
